﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Uranus.Common
{
    public class Validates
    {
        /// <summary>
        /// 转换为Int类型
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int GetInt(object str)
        {
            string s = GetString(str);
            int a = 0;
            int.TryParse(s, out a);
            return a;
        }
        /// <summary>
        /// 转换为字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetString(object str)
        {
            if (str == null)
            {
                return string.Empty;
            }
            return System.Web.HttpUtility.UrlDecode(str.ToString());
        }

        /// <summary>
        /// 将对象转换为时间格式,如果不是时间格式则返回给定的默认时间
        /// </summary>
        /// <param name="obj">要转换的对象</param>
        /// <param name="defaultReturn">默认时间</param>
        /// <returns></returns>
        public static DateTime GetDateTime(object obj)
        {
            DateTime defaultReturn = DateTime.Now;
            if (IsDateTime(obj))
            {
                return DateTime.Parse(obj.ToString().Trim());
            }
            else
            {
                return defaultReturn;
            }
        }
        /// <summary>
        /// 检测是否是时期类型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool IsDateTime(object obj)
        {
            if (obj == null)
            {
                return false;
            }
            if (string.IsNullOrEmpty(obj.ToString()))
            {
                return false;
            }
            DateTime time;
            return DateTime.TryParse(obj.ToString().Trim(), out time);
        }
        /// <summary>
        /// 获取数字 包括小数
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="defaultReturn"></param>
        /// <returns></returns>
        public static decimal GetDecimal(object obj)
        {
            decimal defaultReturn = 0;
            decimal num = 0m;
            string n = GetString(obj);
            Match m = Regex.Match(n, "^([\\d\\.]+)");
            if (m.Success)
            {
                n = m.Result("$1");
            }
            if (!decimal.TryParse(n, out num))
            {
                num = defaultReturn;
            }
            return num;
        }

        /// <summary>
        /// 匹配url
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool IsUri(string url)
        {
            return new Regex(@"(http\:\/\/)?([\w.]+)(\/[\w- \.\/\?%&=]*)?").IsMatch(url);
        }

        /// <summary>
        /// 判断是否为正确的手机号
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public static bool IsValidMobile(string mobile)
        {
            if (string.IsNullOrEmpty(mobile)) return false;
            const string pattern = @"\b1\d{10}\b";
            return Regex.Match(mobile, pattern, RegexOptions.Compiled).Success;
        }

        #region 身份证号码验证

        static readonly string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";

        /// <summary>
        /// 验证输入是否为有效的身份证号码
        /// </summary>
        /// <param name="Id">要验证的身份证号码</param>
        /// <returns></returns>
        public static bool IsCard(string Id)
        {
            //,out string address
            //address = "";
            //if (Id.Length > 2)
            //{
            //    address = "身份证号码不正确!";
            //}
            if (Id.Length == 18)
            {
                bool check = CheckIDCard18(Id);
                return check;
            }
            else if (Id.Length == 15)
            {
                bool check = CheckIDCard15(Id);
                return check;
            }
            else
            {
                return false;
            }
        }

        private static bool CheckIDCard18(string Id)
        {
            long n = 0;
            if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证
            }
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证
            }
            string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = Id.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
            {
                return false;//校验码验证
            }
            return true;//符合GB11643-1999标准
        }

        private static bool CheckIDCard15(string Id)
        {
            long n = 0;
            if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
            {
                return false;//数字验证
            }
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证
            }
            string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            return true;//符合15位身份证标准
        }

        #endregion

        #region 银行卡号验证

        /** 
     * 校验银行卡卡号 
     * @param cardId 
     * @return 
     */
        public static bool CheckBankCard(String cardId)
        {
            char bit = GetBankCardCheckCode(cardId.Substring(0, cardId.Length - 1));

            if (bit == 'N')
            {
                return false;
            }
            return cardId[cardId.Length - 1] == bit;
        }


        /** 
         * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位 
         * @param nonCheckCodeCardId 
         * @return 
         */
        public static char GetBankCardCheckCode(String nonCheckCodeCardId)
        {
            if (nonCheckCodeCardId == null || nonCheckCodeCardId.Trim().Length == 0
                    || !Regex.IsMatch(nonCheckCodeCardId, "\\d+"))
            {
                //如果传的不是数据返回N 
                return 'N';
            }
            char[] chs = nonCheckCodeCardId.Trim().ToCharArray();
            int luhmSum = 0;
            for (int i = chs.Length - 1, j = 0; i >= 0; i--, j++)
            {
                int k = chs[i] - '0';
                if (j % 2 == 0)
                {
                    k *= 2;
                    k = k / 10 + k % 10;
                }
                luhmSum += k;
            }
            return (luhmSum % 10 == 0) ? '0' : (char)((10 - luhmSum % 10) + '0');
        }

        #endregion


        public static string GetJoinString(int[] strArr, string join)
        {
            if (strArr == null || strArr.Length == 0)
                return string.Empty;

            StringBuilder strJoin = new StringBuilder();
            for (int i = 0; i < strArr.Length; i++)
            {
                strJoin.Append(strArr[i]);
                if (i < strArr.Length - 1)
                {
                    strJoin.Append(join);
                }
            }
            return strJoin.ToString();
        }

        /// <summary>
        /// 拼接字符数组用字符隔开
        /// </summary>
        /// <param name="strArr"></param>
        /// <param name="join"></param>
        /// <returns></returns>
        public static string GetJoinString(string[] strArr, string join)
        {
            if (strArr == null || strArr.Length == 0)
                return string.Empty;

            StringBuilder strJoin = new StringBuilder();
            for (int i = 0; i < strArr.Length; i++)
            {
                strJoin.Append(strArr[i]);
                if (i < strArr.Length - 1)
                {
                    strJoin.Append(join);
                }
            }
            return strJoin.ToString();
        }


        /// <summary>
        /// 在字符串中间插入字符
        /// </summary>
        /// <returns></returns>
        public static string InsertChar(string origstr, string schar, int len)
        {
            string str = origstr;
            if (origstr.IndexOf(".") > -1)
            {
                origstr = origstr.Split('.')[0];
            }

            if (origstr.Length == 0)
                return string.Empty;

            if (origstr.Length <= 3)
                return origstr;

            StringBuilder sb = new StringBuilder();
            int a = 0;
            for (int i = origstr.Length - 1; i >= 0; i -= len)
            {
                int maxj = len;
                if ((i + 1) < len)
                {
                    maxj = (i + 1);
                }
                for (int j = 0; j < maxj; j++)
                {
                    sb.Insert(0, origstr[i - j]);
                }
                if (i >= len)
                {
                    sb.Insert(0, schar);
                }
            }
            if (str.IndexOf(".") > -1)
            {
                sb.Append("." + str.Split('.')[1]);
            }
            return sb.ToString();
        }


        /// <summary>
        /// 先去除字符串中所有的空格,再判断字符串是否为空
        /// </summary>
        /// <param name="str"></param>
        /// <returns>true:空 false:非空</returns>
        public static bool WipeoffBlank(string str)
        {
            string s = string.Empty;
            if (!string.IsNullOrEmpty(str))
            {
                s = str.Replace(" ", "");
            }
            else
            {
                return true;
            }
            bool result = string.IsNullOrEmpty(s);
            return result;
        }

        /// <summary>
        /// 去除一切HTML标记
        /// <code>但不去除标记内的内容</code>
        /// </summary>
        /// <param name="obj">要检查的内容</param>
        /// <returns></returns>
        public static string ClearHtml(object obj)
        {
            string html = GetString(obj);
            html = Regex.Replace(html, "(<(.[^>]*)>|[&|#]+[a-zA-Z0-9]+;|[\n\r])", "");
            html = Regex.Replace(html, "(\\s+)", " ");
            return html;
        }

        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="str">要截取的字符串</param>
        /// <param name="length">要截取的长度</param>
        /// <param name="showSign">是否显示(...)</param>
        /// <param name="zjshow">是否字节截取</param>
        /// <returns></returns>
        public static string SubString(string str, int length, bool showSign, bool zjshow)
        {
            if (zjshow)
            {
                int len = 0, j = 0;
                if (!string.IsNullOrEmpty(str))
                {
                    string m = "";
                    char[] strs = str.ToString().ToCharArray();
                    for (int tt = 0; tt < strs.Length; tt++)
                    {
                        if (Convert.ToInt32(strs[tt]) > 255)
                        {
                            len += 2;
                        }
                        else
                        {
                            len++;
                        }
                        if (len > length)
                        {
                            m = str.ToString().Substring(0, j);
                            if (showSign)
                            {
                                m = m + "...";
                            }
                            return m;
                        }
                        j++;
                    }
                }
                return GetString(str);
            }
            else
            {
                return SubString(str, length, showSign);
            }
        }

        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="str">要截取的字符串</param>
        /// <param name="length">要截取的长度</param>
        /// <param name="showSign">是否显示(...)</param>
        /// <returns></returns>
        public static string SubString(string str, int length, bool showSign)
        {
            string s = GetString(str);
            if (s.Length > 0 && s.Length > length)
            {
                string retStr = string.Empty;
                if (s.Length > length)
                {
                    if (showSign)
                    {
                        retStr = s.Substring(0, length).ToString() + "...";
                    }
                    else
                    {
                        retStr = s.Substring(0, length).ToString();
                    }
                }
                else
                {
                    retStr = s;
                }
                return retStr;
            }
            else
            {
                return s;
            }
        }

        /// <summary>  
        /// 当前时间转化为本月的第几周  
        /// </summary>  
        /// <param name="dtSel">指定的日期</param>  
        /// <param name="sundayStart">是否从周日开始计算</param>  
        /// <returns></returns>  
        public static int WeekOfTime(DateTime dtSel, bool sundayStart)
        {
            //如果要判断的日期为1号，则肯定是第一周了   
            if (dtSel.Day == 1) return 1;
            else
            {
                //得到本月第一天   
                DateTime dtStart = new DateTime(dtSel.Year, dtSel.Month, 1);
                //得到本月第一天是周几   
                int dayofweek = (int)dtStart.DayOfWeek;
                //如果不是以周日开始，需要重新计算一下dayofweek，详细风DayOfWeek枚举的定义   
                if (!sundayStart)
                {
                    dayofweek = dayofweek - 1;
                    if (dayofweek < 0) dayofweek = 7;
                }
                //得到本月的第一周一共有几天   
                int startWeekDays = 7 - dayofweek;
                //如果要判断的日期在第一周范围内，返回1   
                if (dtSel.Day <= startWeekDays) return 1;
                else
                {
                    int aday = dtSel.Day + 7 - startWeekDays;
                    return aday / 7 + (aday % 7 > 0 ? 1 : 0);
                }
            }
        }


        /// <summary>
        /// 2.0网站使用的隐藏用户名的方法
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public static string SetUserName(string username)
        {
            if (!String.IsNullOrEmpty(username) && username.Length > 3)
            {
                StringBuilder sbUserName = new StringBuilder();
                char[] uns = username.ToCharArray();
                for (int i = 0; i < uns.Length; i++)
                {
                    if (i < 3 || i == (uns.Length - 1))
                        sbUserName.Append(uns[i]);
                    else if (i < 11)  //隐藏用户名 最多显示12个字符
                        sbUserName.Append("*");
                }
                username = sbUserName.ToString();
            }
            return username;
        }

        /// <summary>
        /// 2.0网站使用的隐藏手机号的方法
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public static string SetHideMobile(string mobile)
        {
            if (!String.IsNullOrEmpty(mobile) && mobile.Length == 11)
            {
                StringBuilder sbMobile = new StringBuilder();
                char[] uns = mobile.ToCharArray();
                for (int i = 0; i < uns.Length; i++)
                {
                    if (i < 3 || i >= (uns.Length - 4))
                        sbMobile.Append(uns[i]);
                    else  //隐藏用户名 
                        sbMobile.Append("*");
                }
                mobile = sbMobile.ToString();
            }
            return mobile;
        }

        /// <summary>
        /// 隐藏身份证的方法
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public static string SetHideIDCard(string idcard)
        {
            if (!String.IsNullOrEmpty(idcard))
            {
                StringBuilder sbidcard = new StringBuilder();
                char[] uns = idcard.ToCharArray();
                for (int i = 0; i < uns.Length; i++)
                {
                    if (i < 4 || i >= (uns.Length - 4))
                        sbidcard.Append(uns[i]);
                    else
                        sbidcard.Append("*");
                }
                idcard = sbidcard.ToString();
            }
            return idcard;
        }

        /// <summary>
        /// 隐藏身份证的方法
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public static string SetHideFullName(string fullName)
        {
            if (!String.IsNullOrEmpty(fullName))
            {
                StringBuilder sbfullname = new StringBuilder();
                char[] uns = fullName.ToCharArray();
                for (int i = 0; i < uns.Length; i++)
                {
                    if (i < 1)
                        sbfullname.Append(uns[i]);
                    else
                        sbfullname.Append("*");
                }
                fullName = sbfullname.ToString();
            }
            return fullName;
        }

        public static string RelaceEmotion(string content)
        {
            if (string.IsNullOrWhiteSpace(content))
                return string.Empty;
            return Regex.Replace(content, @"\[:([a-z0-9]+/[a-zA-Z]{1}_[a-zA-Z0-9]+):\]",
                                 "<img width='33px' src=\"//f.dtcash.com/file/image/bbs/biaoqing/images/$1.gif\" />");
        }

        private readonly static Regex mobileReg = new Regex(@"^1{1}[3-9]{1}[0-9]{9}", RegexOptions.IgnoreCase);
        /// <summary>
        /// 验证是否是手机
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public static bool IsMobile(string mobile)
        {
            return mobileReg.IsMatch(mobile);
        }
    }
}
